<template>
	<SlotModal ref='slotModalRef' v-bind='slotModalConfig'>
		<n-form ref='formRef' v-bind='formConfig'
				:model='formData' :rules='formRules'>
			<n-grid :x-gap='24' :cols='1'>
				<n-form-item-gi span='24' label='上级部门编码' path='parentDeptCode'>
					<n-input v-model:value='formData.parentDeptCode' type='text' disabled/>
				</n-form-item-gi>
				<n-form-item-gi span='24' label='部门编码' path='deptCode'>
					<n-input v-model:value='formData.deptCode'
							 disabled type='text' placeholder='请输入部门编码'/>
				</n-form-item-gi>
				<n-form-item-gi span='24' label='部门名称' path='deptName'>
					<n-input v-model:value='formData.deptName'
							 type='text' placeholder='请输入部门名称'
							 clearable/>
				</n-form-item-gi>
				<n-form-item-gi span='24' label='部门简称' path='deptAbbName'>
					<n-input v-model:value='formData.deptAbbName'
							 type='text' placeholder='请输入部门简称'
							 clearable/>
				</n-form-item-gi>
				<n-form-item-gi span='24' label='部门电话' path='deptPhone'>
					<n-input v-model:value='formData.deptPhone'
							 type='text' placeholder='请输入部门电话'
							 clearable/>
				</n-form-item-gi>
				<n-form-item-gi span='24' label='部门地址' path='deptAddress'>
					<n-input v-model:value='formData.deptAddress'
							 type='text' placeholder='请输入部门地址'
							 clearable/>
				</n-form-item-gi>
				<n-form-item-gi span='24' label='是否禁用' path='disabled'>
					<n-switch v-model:value='formData.disabled as boolean'>
						<template v-slot:checked>是</template>
						<template v-slot:unchecked>否</template>
					</n-switch>
				</n-form-item-gi>
				<n-form-item-gi span='24' label='排序' path='sort'>
					<n-input-number v-model:value='formData.sort' placeholder='请输入排序序号'
									style='width:100%;' min='0' clearable/>
				</n-form-item-gi>
				<n-form-item-gi span='24'>
					<n-flex justify='center' style='width:100%;'>
						<n-button type='primary' @click='submitEvent'>
							提交
						</n-button>
						<n-button type='info' @click='resetEvent'>
							重置
						</n-button>
					</n-flex>
				</n-form-item-gi>
			</n-grid>
		</n-form>
	</SlotModal>
</template>
<script lang='ts' setup>
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
// axios
import axios from '@/config/axios/index.ts';
// 模态框和打印组件
import { VxeUI } from '@/config/vxe/index.ts';
import type { JsonResultProps } from '#/JsonResult.d.ts';
import { FormInst, FormProps, FormRules, FormValidationError } from 'naive-ui';
import type {
	DeptMaintainInfoProps, DeptMaintainProps
} from '#/src/components/page/systemManager/deptMaintain/DeptMaintainProps.d.ts';
const SlotModal = defineAsyncComponent(() => import('@/components/customComponents/modal/SlotModal.vue'));
// 接收的参数
const props = defineProps({
	reLoad : {
		type    : Function,
		require : true,
		default : null
	}
});
// 模态框的配置
const slotModalConfig = reactive({
	reLoad            : () => props.reLoad(),
	onOpenModalEvent  : () => onOpenModalEvent(),
	onCloseModalEvent : () => onCloseModalEvent(),
	resetEvent        : () => clearFormData()
});
// 表单配置
const formConfig = reactive<FormProps>({
	labelWidth           : 'auto',
	labelAlign           : 'left',
	labelPlacement       : 'left',
	size                 : 'large',
	requireMarkPlacement : 'right-hanging'
});
// 表单绑定数据
const formData = reactive<DeptMaintainInfoProps>({
	tenantCode     : null,
	parentDeptCode : null,
	deptCode       : null,
	deptName       : null,
	deptAbbName    : null,
	deptPhone      : null,
	deptAddress    : null,
	disabled       : null,
	sort           : null
});
const currentRowData = reactive<DeptMaintainInfoProps>({
	tenantCode     : null,
	parentDeptCode : null,
	deptCode       : null,
	deptName       : null,
	deptAbbName    : null,
	deptPhone      : null,
	deptAddress    : null,
	disabled       : null,
	sort           : null
});
// 表单校验规则
const formRules = reactive<FormRules>({
	parentDeptCode : {
		required : true,
		trigger  : ['input', 'blur'],
		message  : '上级部门编码是必须的'
	},
	deptCode       : {
		required : true,
		trigger  : ['input', 'blur'],
		message  : '请输入部门编码'
	},
	deptAbbName    : {
		required : true,
		trigger  : ['input', 'blur'],
		message  : '请输入部门简称'
	},
	deptName       : {
		required : true,
		trigger  : ['input', 'blur'],
		message  : '请输入部门全称'
	},
	sort           : {
		required : true,
		type     : 'number',
		trigger  : ['input', 'blur'],
		message  : '请输入序号'
	}
});
const slotModalRef = ref<InstanceType<typeof SlotModal>>();
const formRef = ref<FormInst>();
onMounted(() => {
	// slotModalRef
	// deptMaintainEditModal
});
const showModal = async (rowData: DeptMaintainInfoProps) => {
	Object.assign(currentRowData, rowData);
	await slotModalRef.value!.openModal({
		height    : '500',
		width     : '700',
		title     : '编辑部门信息',
		showClose : true
	});
};
const onOpenModalEvent = async () => {
	console.log(currentRowData);
	return new Promise((resolve, reject): void => {
		axios<any, JsonResultProps<any>, any>({
			method : 'GET',
			url    : `/department/detail/${currentRowData.tenantCode}/${currentRowData.deptCode}`,
			data   : formData
		}).then((jsonResult: JsonResultProps<any>) => {
			if (jsonResult.status) {
				const data: DeptMaintainProps = jsonResult.data;
				formData.tenantCode = data.tenantCode;
				formData.parentDeptCode = data.parentDeptCode;
				formData.deptCode = data.deptCode;
				formData.deptName = data.deptName;
				formData.deptAbbName = data.deptAbbName;
				formData.deptPhone = data.deptPhone;
				formData.deptAddress = data.deptAddress;
				formData.disabled = data.disabled;
				formData.sort = data.sort;
				resolve(null);
			} else {
				VxeUI.modal.message({
					content : jsonResult['msg'],
					status  : 'warning',
					id      : 'failedMessage'
				});
				reject();
			}
		}).catch((error: unknown) => {
			console.error(error);
			VxeUI.modal.message({
				content : '系统异常,请稍后再试',
				status  : 'error',
				id      : 'errorMessage'
			});
			reject();
		});
	});
};
const onCloseModalEvent = async () => {
	await clearFormData();
};
const resetEvent = async () => {
	// 清理表单数据
	Object.assign(formData, {
		id       : null,
		deptCode : null,
		deptName : null,
		fullName : null,
		abbName  : null,
		disabled : false
	});
	// 去除表单校验提示
	formRef.value?.restoreValidation();
};
const clearFormData = async () => {
	// 清理表单数据
	Object.assign(formData, {
		mode           : null,
		parentId       : null,
		id             : null,
		parentDeptCode : null,
		deptCode       : null,
		deptName       : null,
		fullName       : null,
		abbName        : null,
		disabled       : false
	});
	// 去除表单校验提示
	formRef.value?.restoreValidation();
};
const submitEvent = async () => {
	// 校验菜单
	formRef.value?.validate((errors?: Array<FormValidationError>): void => {
		if (errors) {
			VxeUI.modal.message({ content : '请先完善填写的内容!', status : 'warning', id : 'validateMessage' });
		} else {
			// 提交数据
			axios<any, JsonResultProps<any>, any>({
				method : 'PUT',
				url    : `/department/${currentRowData.tenantCode}/${currentRowData.deptCode}`,
				data   : formData
			}).then((jsonResult: JsonResultProps<any>) => {
				if (jsonResult['status']) {
					// 提示用户
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'success',
						id      : 'successMessage'
					});
					// 刷新数据
					props.reLoad(null);
					slotModalRef.value!.closeModal();
				} else {
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'warning',
						id      : 'failedMessage'
					});
				}
			}).catch((error: unknown) => {
				console.error(error);
				VxeUI.modal.message({
					content : '系统异常,请稍后再试',
					status  : 'error',
					id      : 'errorMessage'
				});
			});
		}
	});
};
// 导出方法
defineExpose({ showModal });
</script>